/**
 *品牌维护管理 create on 2017/8/21.
 */
var current_upload = '';                                                        //当前上传的是哪张图片
var current_mode = '';                                                          //当前编辑模式   ADD,MOD,VIEW

$(document).ready(function(){
    $.fn.dataTable.ext.errMode = 'none';
    $('#table_list').on('xhr.dt',function(e, settings, techNote, message) {
    	var error_message = message.responseText;
    	var start_length = error_message.indexOf('||--');
    	var end_length = error_message.indexOf('--||')  ;
    	
    	if(start_length > 0 && end_length > 0){
    		error_message = error_message.substring(start_length+4,end_length);
        	$.jBox.error(error_message, '错误');
    	}
        return false;
    } ).DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'/static/plugins/datatables/language.json?ver=001'
        },
        "sScrollY" : 400, //DataTables的高
        "scrollY": "100%",
        "scrollX": "100%",
        "scrollCollapse": "true",
        "paging": "false",
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/goods-brand/get-brand-list',
            type:'post',
            data:function(d){
                d.brand_name = $('#search_brand_name').val();
                d.tag = $('#tag').val();
            },
            error:getError
        },
        aoColumns: [
            { "data": "", "bSortable": false},
            { "data": "id", "bSortable": true},
            { "data": "brand_name", "bSortable":false },
            { "data": "brand_desc", "bSortable":false },
            { "data": "use_flg", "bSortable":false }
        ],
        columnDefs: [
            {
                "targets": [0],
                "render": function(data, type, full) {
                    return '<a href="javascript:" onclick="updateBrand('+ full.id +')">修改</a>';
                }
            },
            {
                "targets": [4],
                "data": "use_flg",
                "render": function(data, type, full) {
                	return '<span class="switch" data-id="'+ full.id +'" data-flg="'+data+'"><input  style="width:20px;height:20px;" type="checkbox" '+(data == 1 ? 'checked="checked"' : '')+' class="input-check"></span>';
                }
            }
        ],
        order: [[ 1, "desc" ]]                      //初始指定排序字段
    });
});

//ICON图片上传按钮事件
$('.upload-img-btn-icon').click(function(){
    current_upload = 'icon';
    $('.upload_file_ot').trigger('click');
});
//LOGO图片上传按钮事件
$('.upload-img-btn-logo').click(function(){
    current_upload = 'logo';
    $('.upload_file_ot').trigger('click');
});
//大图图片上传按钮事件
$('.upload-img-btn-img').click(function(){
    current_upload = 'img';
    $('.upload_file_ot').trigger('click');
});
//手机大图图片上传按钮事件
$('.upload-img-btn-img-wap').click(function(){
    current_upload = 'wap';
    $('.upload_file_ot').trigger('click');
});

$('.upload_file_ot').change(function(){
    if(this.value == ''){

    }else{
        $('#upload_form_update').submit();
    }
});

//提交品牌数据(添加/编辑)
$('.ajax_submit').click(function(){
    if(!checkInput()){
        return;
    }
    $.post($('#group_form').attr('action'),$('#group_form').serialize(),success,'json');
    return false;
    function success(data){
        $.jBox.close();
        $('#myModal').modal('hide');
        if(data.code == 200)
        {
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () { reload(); }, 1000);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
    }
});

/**
 * 校验输入项
 * @returns {boolean}
 */
function checkInput(){

    if(  $('#brand_name').val() == ''){
        $.jBox.error('请输入品牌名称', '错误');
        return false;
    }

//    if($('#country_name').val().trim() == ''){
//        $.jBox.error('请输入国家名称', '错误');
//        return false;
//    }

    //标签如果选择新建，则判断是否输入
    if($("#tag_list").val() == 'new' && $('#new_tag').val().trim() == ''){
        $.jBox.error('请输入新标签名称', '错误');
        return false;
    }
    return true;
}

/**
 * 图片上传动作
 **/
$('#upload_form_update').submit(function(e){
    e.preventDefault();
    $(this).ajaxSubmit({
        beforeSend:function(){
            if(current_upload == 'icon'){
                $('.upload-img-btn-icon').attr('disabled',true);
            }else if(current_upload == 'logo'){
                $('.upload-img-btn-logo').attr('disabled',true);
            }else if(current_upload == 'img'){
            	$('.upload-img-btn-img').attr('disabled',true);
            }else if(current_upload == 'wap'){
            	$('.upload-img-btn-img-wap').attr('disabled',true);
            }
        },
        success:function(data){
            var result = $.parseJSON(data);
            if(result.code == 500){
                $.jBox.error(result.val, '错误');
            }else{
                if(current_upload == 'icon'){
                    $('.show-img-btn-icon').attr('data-img','');
                    $('.show-img-btn-icon').hide();
                    $('.upload-img-btn-icon').attr('disabled',false);
                    $('.show-img-btn-icon').attr('data-img',result.val);
                    $('#country_icon').val(result.val);
                    $('.show-img-btn-icon').show();
                }else if(current_upload == 'logo'){
                    $('.show-img-btn-logo').attr('data-img','');
                    $('.show-img-btn-logo').hide();
                    $('.upload-img-btn-logo').attr('disabled',false);
                    $('.show-img-btn-logo').attr('data-img',result.val);
                    $('#img_url_logo').val(result.val);
                    $('.show-img-btn-logo').show();
                }else if(current_upload == 'img'){
                	$('.show-img-btn-img').attr('data-img','');
                    $('.show-img-btn-img').hide();
                    $('.upload-img-btn-img').attr('disabled',false);
                    $('.show-img-btn-img').attr('data-img',result.val);
                    $('#main_img').val(result.val);
                    $('.show-img-btn-img').show();
                }else if(current_upload == 'wap'){
                	$('.show-img-btn-img-wap').attr('data-img','');
                    $('.show-img-btn-img-wap').hide();
                    $('.upload-img-btn-img-wap').attr('disabled',false);
                    $('.show-img-btn-img-wap').attr('data-img',result.val);
                    $('#main_img_wap').val(result.val);
                    $('.show-img-btn-img-wap').show();
                }
                $('input[type=file]').closest('form').get(0).reset();
            }
        }
    });
});

//查看图片
$('.show-img-btn-icon , .show-img-btn-logo , .show-img-btn-img , .show-img-btn-img-wap').click(function(){
    var img_url = $(this).attr('data-img');
    showMoreImg(img_url);
});

//查询处理
$('#select_button').click(function(){
    var table = $('#table_list').DataTable();
    table.ajax.reload();
});

/**
 * 显示图片
 **/
function showMoreImg(objKey){
    if(objKey == '' || objKey == null || objKey == undefined){
        $.jBox.error('数据为空', '错误');
        return;
    }
    var json = {
        "title": "图片", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",//图片名
                "pid": 0, //图片id
                "src": $('#imageBathUrl').val()  + objKey, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json
    });
}
//编辑品牌
function updateBrand(id){
    current_mode = 'MOD';                                //当前为查看模式
    $('#current_mode').val(current_mode);
    reloadTag(id);

}
//查看品牌详情
function viewBrand(id){
    current_mode = 'VIEW';                                //当前为查看模式
    $('#current_mode').val(current_mode);
    loadBrandData(id);
}
//加载数据
function loadBrandData(id){
    $.ajax({
        type: "post",
        dataType: "json",
        url:'/goods-brand/brand-view',
        data: {id:id},
        success: function (data) {
            if(data.code == 200){
                setValue(data);                                          //设置内容
                $('#myModal').modal('show');
            }else{
                $.jBox.error(data.val, '错误');
            }
        }
    });
}
//设置控件内容
function setValue(data){
    if(current_mode == 'ADD'){
        $('#myModalLabel').html('添加品牌');
        $('.ajax_submit').show();                          //隐藏提交按钮
        return;
    }

    var brand_data = JSON.parse(data.val);                  //后端JSON字符串转JSON对像
    $("#brand_id").val(brand_data['id']);                 //品牌ID

    if(current_mode == 'VIEW'){
        $('#myModalLabel').html('查看品牌');
        $("#tag_list").hide();                              //隐藏标签下拉框
        $('.ajax_submit').hide();                          //隐藏提交按钮
        $("#new_tag").show();                               //显示新建标签输入框，为了显示标签值
    }
    if(current_mode == 'MOD'){
        $('#myModalLabel').html('编辑品牌');
        $("#new_tag").hide();                               //显示新建标签输入框，为了显示标签值
        $("#tag_list").show();                              //隐藏标签下拉框
        $("#tag_list").val(brand_data['tag']);
        $('.ajax_submit').show();                          //隐藏提交按钮
    }

    $("#brand_name").val(brand_data['brand_name']);
    $("#brand_desc").val(brand_data['brand_desc']);
    $('#brand_story').val(brand_data['brand_story']);
    $('#video_url_pc').val(brand_data['video_url_pc']);
    $('#video_url_wap').val(brand_data['video_url_wap']);
    $("#country_name").val(brand_data['country_name']);
    $("#new_tag").val(brand_data['tag']);
    $("#use_flg").val(brand_data['use_flg']);
    $('#store_location').val(brand_data['store_location']);
    if(brand_data['country_icon'] != ''){
        $('.show-img-btn-icon').attr('data-img',brand_data['country_icon']);
        $('#country_icon').val(brand_data['country_icon']);
        $('.show-img-btn-icon').show();
    }else{
        $('.show-img-btn-icon').attr('data-img','');
        $('#country_icon').val('');
        $('.show-img-btn-icon').hide();
    }
    if(brand_data['logo'] != ''){
        $('.show-img-btn-logo').attr('data-img',brand_data['logo']);
        $('#img_url_logo').val(brand_data['logo']);
        $('.show-img-btn-logo').show();
    }else{
        $('.show-img-btn-logo').attr('data-img','');
        $('#img_url_logo').val('');
        $('.show-img-btn-logo').hide();
    }
    if(brand_data['main_img'] != '' && brand_data['main_img'] != null){
        $('.show-img-btn-img').attr('data-img',brand_data['main_img']);
        $('#main_img').val(brand_data['main_img']);
        $('.show-img-btn-img').show();
    }else{
        $('.show-img-btn-img').attr('data-img','');
        $('#main_img').val('');
        $('.show-img-btn-img').hide();
    }
    if(brand_data['main_img_wap'] != '' && brand_data['main_img_wap'] != null){
        $('.show-img-btn-img-wap').attr('data-img',brand_data['main_img_wap']);
        $('#main_img_wap').val(brand_data['main_img_wap']);
        $('.show-img-btn-img-wap').show();
    }else{
        $('.show-img-btn-img-wap').attr('data-img','');
        $('#main_img_wap').val('');
        $('.show-img-btn-img-wap').hide();
    }
    $('#input_table_keyword').html('');
    if(brand_data['keyword_name'] != '' && brand_data['keyword_name'] != null && brand_data['keyword_name'] != undefined){
    	var akeyword = [];
    	akeyword = brand_data['keyword_name'].split(',');
        for (i=0;i<akeyword.length ;i++ ){
        	var html = '';
        	var class_len = $('#class_len').val();
            var div_class = 'dropdown-sin-'+class_len;
    		html += '<tr><td>';
    		//mod by lizenan 20180126 【后台需求】品牌管理关键词维护修改   484  start
//        	html += '<div class="'+div_class+'">';
//       	 	html += '<select style="display:none" name="keyword[]" placeholder="请选择">';
//       	 	if(keyword_data.length > 0){
//            	keyword_data.forEach(function(data,index){
//            		html += '<option value="'+data.name+'" '+(data.name == akeyword[i] ? 'selected' : '')+'>'+data.name+'</option>';
//                });
//       	 	}
//        	html += '</select>';
//        	html += '</div>';
    		html += '<input value="'+akeyword[i]+'" class="form-control" name="keyword[]" type="text">';
        	html += '</td>';
        	html += '<td><a class="del_input_table_tr" href="javascript:;">删除</a></td> </tr>';
        	class_len++;
            $('#class_len').val(class_len);
            $('#input_table_keyword').append(html);
//            $('.'+div_class).dropdown({
//              readOnly: true,
//              input: '<input type="text" maxLength="20" placeholder="请输入搜索">'
//            });
          //mod by lizenan 20180126 【后台需求】品牌管理关键词维护修改   484  end
    	}
    }
}
//标签下拉框选择事件
$("#tag_list").change(function(){
    if($(this).val() == 'new'){
        $("#new_tag").css('display','block');
    }else{
        $("#new_tag").css('display','none');
    }
});

//重置操作
$('#reset_button').click(function(){
    $('#search_brand_name').val('');
    $('#tag').val('');
    var table = $('#table_list').DataTable();
    table.ajax.reload();
});

//重新加载数据
function reload(){
    var table = $('#table_list').DataTable();
    table.ajax.reload();
}

//添加品牌
$('#add_button').click(function(){
    current_mode = 'ADD';
    $('#current_mode').val(current_mode);
    resetValue();                                   //重置控件
    setValue();
    reloadTag(0);
    $('#myModal').modal('show');
});

/**
 * 重置编辑层数据
 */
function resetValue(){
    if(current_mode == 'ADD'){
        $('#myModalLabel').html('添加品牌');
    }

    if(current_mode == 'VIEW'){
        $('#myModalLabel').html('查看品牌');
    }
    if(current_mode == 'MOD'){
        $('#myModalLabel').html('编辑品牌');
    }

    $('#myModalLabel').html('');
    $("#brand_name").val('');
    $("#brand_desc").val('');
    $('#brand_story').val('');
    $("#country_name").val('');
    $("#new_tag").val('');
    $("#new_tag").hide();
    $("#use_flg").val('1');
    $("#tag_list").show();
    $('.show-img-btn-icon').attr('data-img','');
    $('#country_icon').val('');
    $('.show-img-btn-icon').hide();

    $('.show-img-btn-logo').attr('data-img','');
    $('#img_url_logo').val('');
    $('.show-img-btn-logo').hide();
    
    $('.show-img-btn-img').attr('data-img','');
    $('#main_img').val('');
    $('.show-img-btn-img').hide();
    
    $('.show-img-btn-img-wap').attr('data-img','');
    $('#main_img_wap').val('');
    $('.show-img-btn-img-wap').hide();
}
/**
 * 刷新标签下拉框数据
 */
function reloadTag(id){
    $.ajax({
        type: "post",
        dataType: "json",
        url:'/goods-brand/get-brand-taglist',
        data: {},
        success: function (data) {
            if(data.code == 200)
            {
                $("#tag_list").empty();                                 //清空数据
            	data['val'].forEach(function (item,index,input) {
                    var value = item['tag'];
                    $("#tag_list").append("<option value='" + value + "'>" + value + "</option>");
                });
                $("#tag_list").append("<option value='new'>新建标签</option>");
                if(id !=0 ){
                    loadBrandData(id);
                }
            }
            else{
                $.jBox.error(data.val, '错误');
            }
        }
    });
}

/**
 * 刷新标签数据
 */
function resetTag(data){
    $("#tag_list").show();
    $("#tag_list").empty();

    JSON.parse(data).forEach(function (item,index,input) {
        var value = item['tag'];
        $("#tag_list").append("<option value='" + value + "'>" + value + "</option>");
    });
    $("#tag_list").append("<option value='new'>新建标签</option>");

}

/**
 * 启用/禁用
 * @param id
 * @param useFlg
 */
function usflgClick(id , useFlg){
    var title = '';
    postUrl = '/goods-brand/change-brand-useflg';

    if(useFlg == 1){
        title = '确定禁用吗？';
        useFlg = 0;
    }else{
        title = '确定启用吗？';
        useFlg = 1;
    }

    $.jBox.confirm(title, "提示", function(v){
        if (v == 'ok'){
            $.post(postUrl,{id:id,useFlg:useFlg},success,'json');
            return false;
            function success(data){
                $.jBox.close();                             //关闭对话框
                if(data.code == 200)
                {
                    $.jBox.tip('处理成功', 'success');
                    window.setTimeout(function () { reload(); }, 1000);
                }
                else{
                    $.jBox.error(data.val, '错误');
                }
            }
        }else{
        	if(useFlg == 1){
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',false);
        	}else{
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',true);
        	}
            $.jBox.close();
        }
    });
}

$("#brand_story").xheditor({
	upImgUrl: '/common/xhedit-upload',
	upImgExt: "jpg,jpeg,gif,bmp,png",
	onUpload:insertUpload
},true);

function insertUpload(arrMsg)
{
	var i,msg;
	for(i=0;i<arrMsg.length;i++)
	{
		msg=arrMsg[i];
		$("#xheImgUrl").html(msg);
	}
}

$('#table_list').on('click','.input-check',function(){
	var id = $(this).parent().attr('data-id');
	var use_flg = $(this).parent().attr('data-flg');
	usflgClick(id,use_flg);
});

//添加关键字
$('#add_input_keyword').click(function(){
    var tr_length = $('#input_table_keyword').find('tr').length;

    var tr_length_ot = 0;

    $('#input_table').find('tr').each(function(){
        var data_length = $(this).attr('data-length');
        if(data_length != '' && data_length != undefined){
            tr_length_ot = eval(data_length);
        }
    })

    if(eval(tr_length_ot) > 0){
        tr_length = tr_length_ot + 1;
    }
    var class_len = $('#class_len').val();
    var div_class = 'dropdown-sin-'+class_len;
    var html = '<tr><td>';
    	html += '<input value="" class="form-control" name="keyword[]" type="text">';
    	//mod by lizenan 20180126 【后台需求】品牌管理关键词维护修改   484  start
//    	html += '<div class="'+div_class+'">';
//   	 	html += '<select style="display:none;width:50%" name="keyword[]" placeholder="请选择">';
//   	 	if(keyword_data.length > 0){
//       	 	keyword_data.forEach(function(data,index){
//        		html += '<option value="'+data.name+'">'+data.name+'</option>';
//            });
//       	}
//    	html += '</select>';
//    	html += '</div>';
    	html += '</td>';
    	html += '<td><a class="del_input_table_tr" href="javascript:;">删除</a></td> </tr>';

    $('#input_table_keyword').append(html);

//    $('.'+div_class).dropdown({
//      readOnly: true,
//      input: '<input type="text" maxLength="20" placeholder="请输入搜索">'
//    });
  //mod by lizenan 20180126 【后台需求】品牌管理关键词维护修改   484  end
    class_len++;
    $('#class_len').val(class_len);
});

$('table').delegate('.del_input_table_tr','click',function(){
    $(this).parent().parent().remove();
})